#include <iostream>
#include <sys/wait.h>
#include <string>
#include <string.h>
#include <unistd.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <fcntl.h>

using namespace std;

#define MY_FIFO "./MY_FIFO"

int main()
{
    //因为权限掩码的原因,所以下面创建的fifo的权限并不是0666
    //而是0664,系统的权限掩码是0002
    //可以使用umask(),进行权限掩码的设置
    //ps:这里的权限掩码的设置,只会影响到这个进程,并不会影响到系统
    umask(0000);

    if (mkfifo(MY_FIFO, 0666) < 0)
    {
        perror("mkfifo fail");
        return 1;
    }

    //以读的方式打开管道
    int read_fd = open(MY_FIFO, O_RDONLY);
    if (read_fd == -1)
    {
        perror("open fail");
        return 2;
    }

    //业务逻辑
    while(1)
    {
        char buffer[64] = {0};
        ssize_t s = read(read_fd, buffer, sizeof(buffer) - 1);
        if (s > 0)
        {
            buffer[s] = '\0';

            if (strcmp(buffer, "show mune") == 0)
            {
                if (fork() == 0)
                {
                    execl("/usr/bin/ls", "ls", "-a", "-l", NULL);
                    exit(0);
                }
                waitpid(-1, NULL, 0);
            }
            else if(strcmp(buffer, "train") == 0)
            {
                if (fork() == 0)
                {
                    execl("/usr/bin/sl", "sl", NULL);
                    break;
                }
                waitpid(-1, NULL, 0);
            }
            else if(strcmp(buffer, "exit") == 0)
            {
                cout << "process exit!" << endl;
                return 0;
            }
            else 
            {
                cout << "client : " << buffer << endl;
            }
        }
        else if (s == 0)
        {
            cout << "client quit!" << endl;
            break;
        }
        else 
        {
            perror("read");
            break;
        }
    }

    close(read_fd);
    unlink(MY_FIFO);
    return 0;
}
